package com.zhku.shoppingspringboot.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){

        String message = ex.getMessage();
        if(message!=null&&message!=""){
            return R.error(ResultCode.ERROR,message);
        }else{
            return R.error(ResultCode.ERROR);
        }

    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptHandler(SQLIntegrityConstraintViolationException ex){
       String duplicateField=ex.getMessage().split(" ")[2];
       String message=duplicateField+"这个字段已经取过了";
        return R.error(ResultCode.HAS_EXIST,message);
    }
    /**
     * 单个参数校验异常处理
     * @param ex
     * @return
     */

    @ExceptionHandler(ConstraintViolationException.class)
    public R<String> handleConstraintViolationException(ConstraintViolationException ex) {
        R<String> respond = R.error(ResultCode.VALIDATE_FAILED);
        for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
            String propertyPath = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            respond.add(propertyPath, message);
        }
        return respond;
    }

    /**
     * 实体类校验异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        R<String> respond = R.error(ResultCode.VALIDATE_FAILED);
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            respond.add(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return respond;
    }


}
